import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer'
import { File } from '@ionic-native/file'
import { FileOpener } from '@ionic-native/file-opener'

@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
export class ContactPage {
  @ViewChild('video_box') video_box
  @ViewChild('video_element') video_ele
  @ViewChild('video_ctrl') video_ctrl
  @ViewChild('progress_box') progress_box
  @ViewChild('progress_bar') progress_bar
  @ViewChild('progress_ctl') progress_ctl
  @ViewChild('buffer_bar') buffer_bar
  @ViewChild('download_btn') download_btn
  @ViewChild('download_box') download_box
  @ViewChild('full_screen') full_screen
  oVideoBox
  oVideo
  oVideoCtrl
  oProgressBox
  oProgressBar
  oProgressCtl
  oBufferBar
  oDownloadBtn
  oDownloadBox
  oFullScreen
  // video_src: string = 'https://cc-west-usa.oss-us-west-1.aliyuncs.com/15404832/1313403631687.mp4'
  // video_src: string = 'http://115.231.152.50/vcloud1049.tc.qq.com/1049_M0139200001jMHza2ei3OY1001122187.f40.mp4?vkey=AF4C7AED87C383EB3910C2871CDA0A0CCC35C5FFB7F506054987945DA7AB70533DD2A8B78AA76C6D6A0A7DDF7C8CD17757AE567467D871FC499885621EB0641EE58626032AF2780C563FC77F558328367BB542961739D33D'
  video_src: string = 'http://221.228.226.5/6/y/b/e/t/ybetiqgngtsqyrvwgcgqrehdwstpmh/hc.yinyuetai.com/0E46014EDD471A7CA26783AB42EC5A03.flv?sc=031ef722a21d7b76&br=776&vid=2340331&aid=5298&area=US&vst=4&ptp=mv&rd=yinyuetai.com'
  video_duration: string = '00.00' // 返回视频的长度（以秒计）
  video_currentTime: string = '00.00' // 设置或返回视频中的当前播放位置（以秒计）
  video_readyState: number = 0 // 返回视频当前的就绪状态[0-4]
  video_loaded: boolean = false // 是否已经可以播放

  progress_bar_width: number = 0
  offset_left: number = 0
  is_full_screen: boolean = false

  // ----------------------------

  fileTransfer: FileTransferObject
  download_percent: number = 0
  date: Date
  format_date: string
  download_action: boolean = false
  download_path: string

  constructor(
    private navCtrl: NavController,
    private file: File,
    private transfer: FileTransfer,
    private fileOpener: FileOpener
  ) {
    this.date = new Date();
    this.format_date = `${this.date.getFullYear()}-${this.date.getMonth() + 1}-${this.date.getDate()}`
    this.initVideoDownload()
  }
  initVideoDownload() {
    try {
      this.fileTransfer = this.transfer.create()
      this.fileTransfer.onProgress((ev: ProgressEvent) => this.download_percent = Math.ceil(ev.loaded / ev.total * 100))
    } catch (error) {
      alert(`initVideoDownload\n${JSON.stringify(error)}`)
    }
    this.getDownloadPath()
  }
  downloadVideo(url: string) {
    if (this.download_action) return alert('正在下载中!')
    this.download_action = true
    try {
      this.fileTransfer.download(url, `${this.file.dataDirectory + this.format_date}-mv.mp4`).then(
        entry => {
          this.download_action = false
          window.localStorage.setItem('video-download-url', entry.toURL()) // 保存下载地址
          this.getDownloadPath()
          alert(`下载完成\n${entry.toURL()}`)
        },
        error => alert(JSON.stringify(error))
      ).catch(error => alert(JSON.stringify(error)))
    } catch (error) {
      alert(`downloadVideo\n${JSON.stringify(error)}`)
    }
  }
  openDownloadDirectory() {
    try {
      this.fileOpener.open(window.localStorage.getItem('video-download-url'), 'video/mp4').then(
        res => console.log('Open the file successfully'),
        err => alert(JSON.stringify(err))
      )
    } catch (error) {
      error => alert(`openDownloadDirectory\n${JSON.stringify(error)}`)
    }
  }
  getDownloadPath() {
    let path = window.localStorage.getItem('video-download-url')
    this.download_path = path || ''
  }

  // ---------------------------------------------------------------------------------

  ionViewDidLoad() {
    this.oVideoBox = this.video_box.nativeElement
    this.oVideo = this.video_ele.nativeElement
    this.oVideoCtrl = this.video_ctrl.nativeElement
    this.oProgressBox = this.progress_box.nativeElement
    this.oProgressBar = this.progress_bar.nativeElement
    this.oProgressCtl = this.progress_ctl.nativeElement
    this.oBufferBar = this.buffer_bar.nativeElement
    this.oDownloadBtn = this.download_btn.nativeElement
    this.oDownloadBox = this.download_box.nativeElement
    this.oFullScreen = this.full_screen.nativeElement
    this.progress_bar_width = this.oProgressBox.offsetWidth
    this.offset_left = this.oProgressBar.getBoundingClientRect().left
    this.initVideo()
    this.oDownloadBtn.onclick = ev => this.downloadVideo(this.video_src)
  }
  initVideo() {
    this.oVideo.onloadeddata = ev => {
      console.log('The video resource is loaded.')
      this.video_duration = this.formatTime((Math.ceil(this.oVideo.duration) / 100))
      this.video_currentTime = this.formatTime(this.oVideo.currentTime)
      this.video_loaded = true
      console.log([this.oVideo])
      this.moveProgressBar()
      this.moveBufferBar()

      this.oVideo.ontimeupdate = ev => {
        this.moveProgressBar()
        this.moveBufferBar()
      }
      this.oProgressCtl.ontouchstart = ev => { }
      this.oProgressCtl.ontouchmove = ev => this.calcCurrentTime(ev.touches[0].clientX)
      this.oProgressCtl.ontouchend = ev => { }
      this.oProgressBox.onclick = ev => this.calcCurrentTime(ev.clientX)
      this.oFullScreen.onclick = ev => {
        if (this.is_full_screen) {
          document['webkitCancelFullScreen']()
          this.is_full_screen = false
        } else {
          this.oVideoBox['webkitRequestFullScreen']()
          this.is_full_screen = true
        }
      }
    }
  }
  calcCurrentTime(clientX: number) {
    this.oVideo.currentTime = this.oVideo.duration * (clientX - this.offset_left) / this.progress_bar_width
    this.moveProgressBar()
  }
  getVideoBuffer() {
    return this.oVideo.buffered.end(0)
  }
  changeCurrentTime() {
    this.video_currentTime = this.formatTime((Math.ceil(this.oVideo.currentTime) / 100))
  }
  moveProgressBar() {
    this.oProgressBar.style.width = `${this.oVideo.currentTime / this.oVideo.duration * 100}%`
    this.changeCurrentTime()
  }
  moveBufferBar() {
    this.oBufferBar.style.width = `${this.oVideo.buffered.end(0) / this.oVideo.duration * 100}%`
  }
  formatTime(time: string | number): string {
    let str = (+time).toFixed(2)
    return str.length < 5 ? `0${str}` : str
  }
  getVideoReadyState() {
    this.video_readyState = this.oVideo.readyState
    return this.video_readyState
  }
  playOrPause() {
    if (!this.video_loaded) return console.warn('The video resource is not loaded!')
    if (this.oVideo.paused) {
      this.oVideo.play()
    } else {
      this.oVideo.pause()
    }
  }

}
